package com.company.project.controller.ldjsc.weather;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.company.project.entity.ldjsc.weather.ZyAirQualityEntity;
import com.company.project.entity.ldjsc.weather.ZyCityCodeEntity;
import com.company.project.entity.ldjsc.weather.ZyCityCodeJuheEntity;
import com.company.project.service.ldjsc.weather.ZyAirQualityService;
import com.company.project.service.ldjsc.weather.ZyCityCodeJuheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.company.project.common.utils.DataResult;


/**
 * 空气质量
 *
 * @author wenbin
 * @email *****@mail.com
 * @date 2025-07-24 09:44:38
 */
@Controller
@RequestMapping("/sxzy")
public class ZyAirQualityController {
    @Autowired
    private ZyAirQualityService zyAirQualityService;
    @Autowired
    private ZyCityCodeJuheService zyCityCodeJuheService;

    @Value("${kqzl.api-juhe.key}")
    private String keyJuhe;
    @Value("${kqzl.api-juhe.url}")
    private String urlJuhe;


    /**
     * 获取指定城市空气质量
     *
     * @param city
     * @return
     */
    @GetMapping("/air/realtime")
    @ResponseBody
    public DataResult getAirQuality(String city) {
        //获取指定城市空气质量
        return DataResult.success(selectByCity(city));
    }

    /**
     * 获取全部城市空气质量
     */
    @GetMapping("/air/realtime/all")
    @ResponseBody
    public DataResult getAirQualityAll() {

        //获取全部城市空气质量
        List<ZyCityCodeJuheEntity> list = zyCityCodeJuheService.list();
        List<ZyAirQualityEntity> airQualityEntities = new ArrayList<>();
        for (ZyCityCodeJuheEntity zyCityCodeJuheEntity : list) {
            String city = zyCityCodeJuheEntity.getCityName();
            ZyAirQualityEntity zyAirQualityEntity = selectByCity(city);
            airQualityEntities.add(zyAirQualityEntity);
        }
        return DataResult.success(airQualityEntities);
    }

    /**
     * 获取城市空气质量
     *
     * @param city
     * @return
     */
    private ZyAirQualityEntity selectByCity(String city) {
        //当前日期不带时间
        LocalDate currentDate = LocalDate.now();
        //获取今天生成的空气质量
        LambdaQueryWrapper<ZyAirQualityEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(ZyAirQualityEntity::getCityName, city);
        queryWrapper.gt(ZyAirQualityEntity::getCreateDate, currentDate);
        queryWrapper.orderByDesc(ZyAirQualityEntity::getCreateDate);
        queryWrapper.last("limit 1");
        ZyAirQualityEntity one = new ZyAirQualityEntity();
        one = zyAirQualityService.getOne(queryWrapper);
        //如果没有数据则获取数据（当前城市）
        if (one == null) {
            LambdaQueryWrapper<ZyCityCodeJuheEntity> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.like(ZyCityCodeJuheEntity::getCityName, city);
            queryWrapper1.last("limit 1");
            ZyCityCodeJuheEntity zyCityCodeJuheEntity = zyCityCodeJuheService.getOne(queryWrapper1);
                getCityAirQuality(zyCityCodeJuheEntity);
        }
        one = zyAirQualityService.getOne(queryWrapper);
        return one;
    }

    //自动生成空气质量（0点10）
    @Scheduled(cron = "0 10 0 * * ?")
    private void automaticTen() {
        List<ZyCityCodeJuheEntity> list = zyCityCodeJuheService.list();
        for (ZyCityCodeJuheEntity zyCityCodeJuheEntity : list) {
            getCityAirQuality(zyCityCodeJuheEntity);
            System.out.println(LocalDateTime.now() + "成功生成：" + zyCityCodeJuheEntity.getCityName() + "空气质量");
        }
    }

    //自动生成空气质量（0点30）
    @Scheduled(cron = "0 30 0 * * ?")
    private void automaticThirty() {
        List<ZyCityCodeJuheEntity> list = zyCityCodeJuheService.list();
        for (ZyCityCodeJuheEntity zyCityCodeJuheEntity : list) {

            LocalDate currentDate = LocalDate.now();
            //获取今天生成的空气质量
            LambdaQueryWrapper<ZyAirQualityEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.like(ZyAirQualityEntity::getCityName, zyCityCodeJuheEntity.getCityName());
            queryWrapper.gt(ZyAirQualityEntity::getCreateDate, currentDate);
            queryWrapper.orderByDesc(ZyAirQualityEntity::getCreateDate);
            queryWrapper.last("limit 1");
            ZyAirQualityEntity zyAirQualityEntity = zyAirQualityService.getOne(queryWrapper);
            if (zyAirQualityEntity == null){
                getCityAirQuality(zyCityCodeJuheEntity);
                System.out.println(LocalDateTime.now() + "成功生成：" + zyCityCodeJuheEntity.getCityName() + "空气质量");
            }
        }
    }


    //    @Scheduled(cron = "0 0 0 * * ?")
    private void getCityAirQuality(ZyCityCodeJuheEntity city) {

        try {
            String requestUrl = urlJuhe + "?key=" + keyJuhe + "&cityId=" + city.getCityCode() + "&output=JSON";

            URL url = new URL(requestUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");

            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            JSONObject result = JSONObject.parseObject(response.toString());
            JSONObject lives = result.getJSONObject("result");

            if (lives == null || lives.isEmpty()) {
                throw new RuntimeException("未获取到空气质量数据");
            }

//                JSONObject airQuality = lives.getJSONObject(0);

            ZyAirQualityEntity entity = new ZyAirQualityEntity();
            entity.setCityName(lives.getString("CityName"));
            entity.setPM25(lives.getString("PM2_5"));
            entity.setAQI(lives.getString("AQI"));
            entity.setQuality(lives.getString("Quality"));
            entity.setPM10(lives.getString("PM10"));
            entity.setNO2(lives.getString("NO2"));
            entity.setCO(lives.getString("CO"));
            entity.setSO2(lives.getString("SO2"));
            entity.setO3(lives.getString("O3"));
            entity.setPrimaryPollutant(lives.getString("PrimaryPollutant"));
            zyAirQualityService.save(entity);

            Thread.sleep(1000); // 控制请求频率
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 跳转到页面
     */
    @GetMapping("/index/zyAirQuality")
    public String zyAirQuality() {
        return "zyairquality/list";
    }


    @ApiOperation(value = "查询分页数据")
    @PostMapping("zyAirQuality/listByPage")
    @SaCheckPermission("zyAirQuality:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody ZyAirQualityEntity zyAirQuality) {
        LambdaQueryWrapper<ZyAirQualityEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        queryWrapper.eq(zyAirQuality.getId() != null, ZyAirQualityEntity::getId, zyAirQuality.getId());
        queryWrapper.orderByDesc(ZyAirQualityEntity::getId);
        IPage<ZyAirQualityEntity> iPage = zyAirQualityService.page(zyAirQuality.getQueryPage(), queryWrapper);
        return DataResult.success(iPage);
    }


    @ApiOperation(value = "新增")
    @PostMapping("zyAirQuality/add")
    @SaCheckPermission("zyAirQuality:add")
    @ResponseBody
    public DataResult add(@RequestBody ZyAirQualityEntity zyAirQuality) {
        zyAirQualityService.save(zyAirQuality);
        return DataResult.success();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("zyAirQuality/delete")
    @SaCheckPermission("zyAirQuality:delete")
    @ResponseBody
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
        zyAirQualityService.removeByIds(ids);
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PutMapping("zyAirQuality/update")
    @SaCheckPermission("zyAirQuality:update")
    @ResponseBody
    public DataResult update(@RequestBody ZyAirQualityEntity zyAirQuality) {
        zyAirQualityService.updateById(zyAirQuality);
        return DataResult.success();
    }


}
